#include "serial.h"
#include "kfifo.h"
//#include "list.h"

#define MAX_SERIAL_NUM  5
typedef struct{
	struct TSerialDevice* serial_dev[MAX_SERIAL_NUM];
	u8 num;
}TSerialMgr;
static TSerialMgr serial_list;
BOOL usart_register(struct TSerialDevice* dev)
{
	if(serial_list.num >= MAX_SERIAL_NUM) return FALSE;

	serial_list.serial_dev[serial_list.num++] = dev;
	return TRUE;
}

u8	usart_portnum()
{
	return serial_list.num;
}
static struct TSerialDevice* usart_get_device(int index)
{
	if( (index > serial_list.num) || (index <= 0)) return NULL;
	index--;
	return serial_list.serial_dev[(index%MAX_SERIAL_NUM)];
}

BOOL usart_open(u8 num,TSerialDesc* desc)
{
	struct TSerialDevice* uart = usart_get_device(num);
	if(uart){
		return uart->open(uart,desc);
	}
	return FALSE;
}
typedef struct TSerialDevice   mydev;
BOOL usart_close(u8 num)
{
	struct TSerialDevice *uart = usart_get_device(num);
	if(uart){
		return uart->close(uart);
	}
	return FALSE;

}
int usart_sendbyte(u8 num,u8 ch)
{
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev){
		return uart_dev->sendbyte(uart_dev,ch);
	}
	return 0;

}
u32 usart_sendstring(u8 num, u8* data, u32 len)
{
	//for(u32 i = 0; i < len; i++)
	//	usart_sendbyte(num,data[i]);
	//return len;
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev){
		return uart_dev->sendstring(uart_dev,data,len);
	}
	return 0;
}

u32 usart_getdatasize(u8 num)
{
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev){
		return uart_dev->getdatasize(uart_dev);
	}
	return 0;
}
u32 usart_getdata(u8 num, u8* data, u32 len, s32 timeout_ms)
{
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev){
		return uart_dev->getstring(uart_dev,data,len,timeout_ms);
	}
	return 0;

}
u32 usart_getpacket(u8 num, u8* data, u32 len)
{
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev && uart_dev->getpacket){
		return uart_dev->getpacket(uart_dev,data,len);
	}
	return 0;
}
BOOL  usart_set_timeout(u8 num,u32 timeout_us)
{	
	struct TSerialDevice *uart_dev = usart_get_device(num);
	if(uart_dev){
		return uart_dev->setpacket_timeout(uart_dev,timeout_us);
	}
	return FALSE;
}



